﻿@using CarParkBooking.Models
@model CarParkBookingModel
@{
    ViewBag.Title = "CarPark";

    var SelectedCarePark = Model.SelectedCarPark;
    DateTime SelectedDate = Model.SelectedMonth;
}


<div style="display:none;" id="dialog-confirm-book" title="Confirm Booking">
  <p>@*<span class="ui-icon ui-icon-alert" style="float: left; margin: 0 7px 20px 0;"></span>*@
  You are about <span id="car-park-name"></span> on <span id="book-date"></span></p>
</div>

<div style="display:none;" id="dialog-confirm-cancel" title="Confirm Cancel Booking">
  <p>@*<span class="ui-icon ui-icon-alert" style="float: left; margin: 0 7px 20px 0;"></span>*@
   Are you sure you want to cancel the booking for <span id="car-park-name"></span> on <span id="book-date"></span>?</p>
</div>

<div class="main-content-title">@ViewBag.Title</div>
<div class="detail-content">
    <div class="choose-carpark no-width">
        Car Park:
        <select class="choose-carpark-combobox" id="cmb_choose_carpark">
            @foreach (var carPark in Model.CarParks)
            {
                if (carPark.ID == Model.SelectedCarPark.ID)
                {
                <option value="@carPark.ID" selected>@carPark.CarParkName</option>
                }
                else
                {
                <option value="@carPark.ID">@carPark.CarParkName</option>
                }
            }
        </select>
    </div>
    <br />
    <br />
    <span id="chosen_car_park">@Model.SelectedCarPark.CarParkName:</span> You have <span
        id="number_remaining_place">
        @Model.RemainingSlotInMonth</span> remaining slots available to book this month.
    Select a slot from the calendar below
    <br />
    <br />
    <div class="car-park-detail">
        <span class="selected-month-title">@Model.SelectedMonth.ToString("MMMM, yyyy")</span>
        <table class="car-park-calendar">
            <tr>
                <td class="car-park-calendar-header">
                    Monday
                </td>
                <td class="car-park-calendar-header">
                    Tuesday
                </td>
                <td class="car-park-calendar-header">
                    Wednesday
                </td>
                <td class="car-park-calendar-header">
                    Thursday
                </td>
                <td class="car-park-calendar-header">
                    Friday
                </td>
            </tr>
            @{
                DateTime CurrentDate = new DateTime(SelectedDate.Year, SelectedDate.Month, 1);
                DateTime EndDayOfMonth = new DateTime(SelectedDate.Year, SelectedDate.Month,
                    DateTime.DaysInMonth(SelectedDate.Year, SelectedDate.Month));
            }
            @while (CurrentDate <= EndDayOfMonth)
            {
                if (CurrentDate.DayOfWeek == DayOfWeek.Saturday || CurrentDate.DayOfWeek == DayOfWeek.Sunday)
                {
                    CurrentDate = CurrentDate.AddDays(1);
                    continue;
                }
                
                <tr class="car-park-calendar-row">
                    @for (DayOfWeek Weekday = DayOfWeek.Monday; Weekday < DayOfWeek.Saturday; Weekday++)
                    {
                        var bookSpace = Model.BookCalendarModels.Where(x => x.BookDate == CurrentDate).First();
                        string calendarCellColor = Model.ColorCodes[bookSpace.RemainingBookSpaces];
                        bool isDayInMonth = false;
                        string style = string.Format("background-color:{0};", Model.ColorCodes[0]);

                        if (CurrentDate.DayOfWeek == Weekday)
                        {
                            if (bookSpace.IsValidDate)
                            {
                                style = string.Format("background-color:{0};cursor: pointer;", calendarCellColor);
                            }

                            isDayInMonth = true;
                        }
                        else
                        {
                            style += "background-color: #DEDEDE;";
                        }

                        if (isDayInMonth)
                        {

                            string bookedBy = string.Empty;

                            if (bookSpace.RemainingBookSpaces < Model.SelectedCarPark.MaxSlotPerDay)
                            {
                                bookedBy = string.Format("Booked by: {0}", string.Join(", ", bookSpace.BookedUsers));
                            }
                        <td id="td-@bookSpace.BookDate.ToString("yyyy_MM_dd")" class="car-park-calendar-cell" style="@style"
                                @{
                            if (bookSpace.IsValidDate)
                            {
                                        <text>onclick="getBookCalendarModel(@SelectedCarePark.ID, '@bookSpace.BookDate.ToString("yyyy_MM_dd")');"</text>
                            }
                                }
                                >
                            <span class="car-park-calendar-cell-title">@CurrentDate.ToString("d MMMM")</span>
                            <span id="span1-@bookSpace.BookDate.ToString("yyyy_MM_dd")" style="font-weight: bold;">@bookSpace.RemainingBookSpaces</span> spaces left.
                            <span id="span2-@bookSpace.BookDate.ToString("yyyy_MM_dd")">@bookedBy</span>
                        </td>
                            CurrentDate = CurrentDate.AddDays(1);
                        }
                        else
                        {
                        <td class="car-park-calendar-cell" style="@style">
                        </td>
                        }
                    }
                </tr>
            }
        </table>
    </div>
</div>
<script type="text/javascript">
    var model;

    $(document).ready(function () {
        $('#cmb_choose_carpark').change(function () {
            var option = this.options[this.selectedIndex];
            $('#chosen_car_park').text($(option).text());

            var selectedCarParkId = $(option).val();

            // get booking data for selected CarPark
            var url = "/Home/CarPark?SelectedCarParkId=" + selectedCarParkId + "&SelectedDate=" 
            + moment(model.SelectedMonth).format("YYYY_MM_DD");
           window.location.href = url;

        });

        model = @Html.Json(Model);
    });

    function getBookCalendarModel(selectedCarParkId, date){
            var methodName = "GetLatestDataForCellCalendar";
            var url = "/Home/" + methodName;
            var date = new Date(Date.fromString(date, {order: 'YMD'}));

            var data = {selectedCarParkId : selectedCarParkId, selectedDate : date };
            var strData = JSON.stringify(data);
            var result;
            $.ajax({
                type: "POST",
                url: url,
               data: strData,
               contentType: "application/json; charset=utf-8",
               dataType: "json",
                success: function(response){
                    onSuccessGetBookCalendarModel(response);
               },
               fail: function(){alert("fail");}
            });
    }

    function onSuccessGetBookCalendarModel(response){
        if (response.status = "ok"){

             var bookCalendarModel = response.data;

            // update current cell calendar
            updateCellCalendar(bookCalendarModel);

             if ( bookCalendarModel ){
                if (bookCalendarModel.CanCancel){
                    // cancel
                    cancelCarParkBookingOnDate(model.SelectedCarPark, bookCalendarModel);
                }else if(bookCalendarModel.CanBook){
                    // book
                    bookCarParkOnDate(model.SelectedCarPark, bookCalendarModel);
                }
             }
        }
    }

    function onFailGetBookCalendarModel(response){
        alert("An error occurred.");
    }

    function updateCellCalendar(bookCalendarModel){
        var suffix = moment(bookCalendarModel.BookDate).format("YYYY_MM_DD");
        var cellId = "td-" + suffix;

        var cell = $("#" + cellId);
        var calendarCellColor = model.ColorCodes[bookCalendarModel.RemainingBookSpaces];

        console.log("calendarCellColor: " + calendarCellColor);
        if (bookCalendarModel.IsValidDate == false){
            $(cell).css("cursor", "");
            $(cell).prop("onclick", null);
        }

        $(cell).css("background-color", calendarCellColor);

        var span1Id = "span1-" + suffix;
        var span1 = $("#" + span1Id).text(bookCalendarModel.RemainingBookSpaces);

        var span2Id = "span2-" + suffix;
        var span2 = $("#" + span2Id);
        if(bookCalendarModel.BookedUsers.length > 0){
           $(span2).text("Booked by: " + bookCalendarModel.BookedUsers.join(", "));
        }else{
            $(span2).text("");
        }
    }

    function updateDataWhenBookCalendarModelChange(model, bookCalendarModel){

        

        var currentBookingDate = moment(bookCalendarModel.BookDate).format("YYYYMMDD");
         
        for(var i = 0; i < model.BookCalendarModels.length; i++){
            var calendarModel =  model.BookCalendarModels[i];

            var strBookDate = moment(calendarModel.BookDate).format("YYYYMMDD");
            if ( strBookDate == currentBookingDate){
                model.BookCalendarModels[i] = bookCalendarModel;
                break;
            }
        }

        var bookingsByUser =  $.grep(model.BookCalendarModels, function(e){
                 return e.IsBookedByYourself == true; });

        console.log("bookingsByUser.length: " + bookingsByUser.length);
        model.RemainingSlotInMonth = model.SelectedCarPark.MaxSlotPerMonth - bookingsByUser.length;
    }

    function cancelCarParkBookingOnDate(selectedCarPark, bookCalendarModel){
        confirmCancelBooking(bookCalendarModel, selectedCarPark);
    }

    function confirmCancelBooking(bookCalendarModel, selectedCarPark){
        $("#car-park-name").text(selectedCarPark.CarParkName);
        $("#book-date").text(moment(bookCalendarModel.BookDate).format("DD MMM"));

        $("#dialog-confirm-cancel").dialog({
          resizable: false,
          //height:140,
          modal: true,
          buttons: {
            "Confirm": function() {
              cancelBookingData(bookCalendarModel, selectedCarPark);
               $( this ).dialog( "close" );
            },
            "Cancel": function() {
              $( this ).dialog( "close" );
            }
          }
        });
        
    }

    function cancelBookingData(bookCalendarModel, selectedCarPark){
        var methodName = "CancelCarParkBooking";
            var url = "/Home/" + methodName;
            var strDate = moment(bookCalendarModel.BookDate).format("YYYY_MM_DD");
            var date = new Date(Date.fromString(strDate, {order: 'YMD'}));

            var data = {selectedCarParkId : selectedCarPark.ID, selectedDate : date };
            var strData = JSON.stringify(data);

            console.log("strData: " + strData);

            var result;
            $.ajax({
                type: "POST",
                url: url,
               data: strData,
               contentType: "application/json; charset=utf-8",
               dataType: "json",
                success: function(response){
                    if (response.status == "ok"){
                        var bookCalendarModel = response.data;

                        // update data for screen
                        updateDataWhenBookCalendarModelChange(model, bookCalendarModel);
                        updateCellCalendar(bookCalendarModel);     
                        
                        // update remaining space
                        getRemainingBookSpaceInMonth(selectedCarPark.ID, strDate);              
                    }
               },
               fail: function(){alert("fail");}
            });
    }

    function bookCarParkOnDate(selectedCarPark, bookCalendarModel){
        confirmBook(bookCalendarModel, selectedCarPark);
    }

    function confirmBook(bookCalendarModel, selectedCarPark){
        $("#car-park-name").text(selectedCarPark.CarParkName);
        $("#book-date").text(moment(bookCalendarModel.BookDate).format("DD MMM"));


        $("#dialog-confirm-book").dialog({
          resizable: false,
          //height:140,
          modal: true,
          buttons: {
            "Confirm": function() {
              saveBookData(bookCalendarModel, selectedCarPark);
               $( this ).dialog( "close" );
            },
            "Cancel": function() {
              $( this ).dialog( "close" );
            }
          }
        });
    }

    function saveBookData(bookCalendarModel, selectedCarPark){
        var methodName = "BookCarPark";
            var url = "/Home/" + methodName;
            var strDate = moment(bookCalendarModel.BookDate).format("YYYY_MM_DD");
            var date = new Date(Date.fromString(strDate, {order: 'YMD'}));

            var data = {selectedCarParkId : selectedCarPark.ID, selectedDate : date };
            var strData = JSON.stringify(data);

            console.log("strData: " + strData);

            var result;
            $.ajax({
                type: "POST",
                url: url,
               data: strData,
               contentType: "application/json; charset=utf-8",
               dataType: "json",
                success: function(response){
                    if (response.status == "ok"){
                         var bookCalendarModel = response.data;

                        // update data for screen
                        updateDataWhenBookCalendarModelChange(model, bookCalendarModel);

                        updateCellCalendar(bookCalendarModel); 
                        
                        // update remaining space
                        getRemainingBookSpaceInMonth(selectedCarPark.ID, strDate);                  
                    }
               },
               fail: function(){alert("fail");}
            });
    }

    function getRemainingBookSpaceInMonth(selectedCarParkId, selectedMonth){
        var methodName = "GetRemaingBookSpacesOfUserInMonth";
            var url = "/Home/" + methodName;
            var data = {selectedCarParkId: selectedCarParkId, selectedMonth : selectedMonth };
            var strData = JSON.stringify(data);

            console.log("strData: " + strData);

            var result;
            $.ajax({
                type: "POST",
                url: url,
               data: strData,
               contentType: "application/json; charset=utf-8",
               dataType: "json",
                success: function(response){
                    if (response.status == "ok"){

                         // update remaing book space in the month
                        $("#number_remaining_place").text(response.data);
                    }
               },
               fail: function(){alert("fail");}
            });
    }
</script>


